document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const dropArea = document.getElementById('drop-area');
    const fileInput = document.getElementById('file-input');
    const fileInfo = document.getElementById('file-info');
    const fileName = document.getElementById('file-name');
    const fileSize = document.getElementById('file-size');
    const removeFile = document.getElementById('remove-file');
    const convertBtn = document.getElementById('convert-btn');
    const uploadProgress = document.getElementById('upload-progress');
    const uploadPercentage = document.getElementById('upload-percentage');
    const progressBar = document.getElementById('progress-bar');
    const conversionStatus = document.getElementById('conversion-status');
    const conversionPercentage = document.getElementById('conversion-percentage');
    const conversionBar = document.getElementById('conversion-bar');
    const statusMessage = document.getElementById('status-message');
    const conversionResult = document.getElementById('conversion-result');
    const successMessage = document.getElementById('success-message');
    const errorMessage = document.getElementById('error-message');
    const errorDetails = document.getElementById('error-details');
    const downloadBtn = document.getElementById('download-btn');
    const retryBtn = document.getElementById('retry-btn');
    const downloadHint = document.getElementById('download-hint');

    // 变量初始化
    let selectedFile = null;
    let taskId = null;
    let statusCheckInterval = null;

    // 拖放功能实现
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    ['dragenter', 'dragover'].forEach(eventName => {
        dropArea.addEventListener(eventName, highlight, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, unhighlight, false);
    });

    function highlight() {
        dropArea.classList.add('active');
    }

    function unhighlight() {
        dropArea.classList.remove('active');
    }

    dropArea.addEventListener('drop', handleDrop, false);

    function handleDrop(e) {
        const dt = e.dataTransfer;
        const file = dt.files[0];
        handleFile(file);
    }

    // 文件选择处理
    fileInput.addEventListener('change', function() {
        if (this.files.length) {
            handleFile(this.files[0]);
        }
    });

    // 处理选中的文件
    function handleFile(file) {
        if (!file.type.match('application/pdf')) {
            showError('请选择PDF文件');
            fileInput.value = '';
            return;
        }

        // 检查文件大小 (500MB)
        if (file.size > 500 * 1024 * 1024) {
            showError('文件大小不能超过500MB');
            fileInput.value = '';
            return;
        }

        selectedFile = file;
        fileName.textContent = file.name;
        fileSize.textContent = formatFileSize(file.size);
        fileInfo.classList.remove('hidden');
        convertBtn.classList.remove('disabled');
    }

    // 移除选中的文件
    removeFile.addEventListener('click', function() {
        selectedFile = null;
        fileInput.value = '';
        fileInfo.classList.add('hidden');
        convertBtn.classList.add('disabled');
    });

    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 显示错误信息
    function showError(message) {
        errorDetails.textContent = message;
        errorMessage.classList.remove('hidden');
        successMessage.classList.add('hidden');
        conversionStatus.classList.add('hidden');
        conversionResult.classList.remove('hidden');
        conversionResult.classList.add('fade-in');
    }

    // 开始转换
    convertBtn.addEventListener('click', function() {
        if (!selectedFile) return;

        uploadFile(selectedFile);
    });

    // 上传文件
    function uploadFile(file) {
        // 确保其他状态区域隐藏
        conversionStatus.classList.add('hidden');
        conversionResult.classList.add('hidden');
        errorMessage.classList.add('hidden');
        successMessage.classList.add('hidden');

        // 显示上传进度
        if (file) {
            uploadProgress.classList.remove('hidden');
            progressBar.style.width = '0%';
            uploadPercentage.textContent = '0%';
            convertBtn.classList.add('disabled');
            removeFile.classList.add('disabled');
        } else {
            // 如果没有文件，确保上传进度区域隐藏
            uploadProgress.classList.add('hidden');
            return;
        }

    // 创建FormData
    const formData = new FormData();
    formData.append('pdf_file', file);
    

    // 使用fetch API发送请求并跟踪进度
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/upload');

    // 上传进度跟踪
    xhr.upload.addEventListener('progress', function(e) {
        if (e.lengthComputable) {
            const percent = Math.round((e.loaded / e.total) * 100);
            progressBar.style.width = percent + '%';
            uploadPercentage.textContent = percent + '%';
        }
    });

    xhr.onload = function() {
        console.log('上传请求响应状态:', xhr.status);
        if (xhr.status === 200) {
            try {
                const data = JSON.parse(xhr.responseText);
                console.log('上传响应:', data);
                if (data.success) {
                    // 上传成功，更新进度到100%，即使实际进度可能不是100%
                    progressBar.style.width = '100%';
                    uploadPercentage.textContent = '100%';
                    taskId = data.task_id;
                    console.log('获取到任务ID:', taskId);

                    // 延迟显示转换状态
                    setTimeout(() => {
                        startConversion(taskId);
                    }, 500);
                } else {
                    showError(data.message || '文件上传失败');
                    resetUI();
                }
            } catch (error) {
                showError('解析服务器响应时出错: ' + error.message);
                resetUI();
            }
        } else {
            showError('上传文件时出错: ' + xhr.statusText);
            resetUI();
        }
    };

    xhr.onerror = function() {
        console.log('上传请求发生网络错误');
        showError('网络错误，上传失败');
        resetUI();
    };

    xhr.send(formData);
};

    // 开始转换
    function startConversion(taskId) {
        console.log('开始转换任务:', taskId);
        // 确保其他状态区域隐藏
        conversionResult.classList.add('hidden');
        errorMessage.classList.add('hidden');
        successMessage.classList.add('hidden');

        // 显示转换状态
        uploadProgress.classList.add('hidden');
        conversionStatus.classList.remove('hidden');
        conversionBar.style.width = '0%';
        conversionPercentage.textContent = '0%';
        statusMessage.textContent = '正在准备转换...';

        // 发送转换请求
        fetch(`/convert/${taskId}`, {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
                if (!data.success) {
                    showError(data.message || '转换失败');
                    // 不重置UI，保持错误界面显示
                    return;
                }

                // 开始检查转换状态和进度
                checkConversionStatus(taskId);
            })
            .catch(error => {
                showError('转换文件时出错: ' + error.message);
                // 不重置UI，保持错误界面显示
            });
    }

    // 检查转换状态和进度
    function checkConversionStatus(taskId) {
        statusCheckInterval = setInterval(() => {
            fetch(`/status/${taskId}`)
                .then(response => response.json())
                .then(data => {
                    console.log('转换状态:', data);
                    if (!data.success) {
                        clearInterval(statusCheckInterval);
                        showError('获取转换状态失败: ' + (data.message || ''));
                        // 不重置UI，保持错误界面显示
                        return;
                    }

                    // 更新进度和状态消息
                    if (data.status === 'converting' && data.progress !== undefined) {
                        conversionBar.style.width = data.progress + '%';
                        conversionPercentage.textContent = data.progress + '%';

                        // 更新状态消息
                        if (data.progress < 30) {
                            statusMessage.textContent = '正在解析PDF文件...';
                        } else if (data.progress < 70) {
                            statusMessage.textContent = '正在转换文档内容...';
                        } else {
                            statusMessage.textContent = '正在生成Word文件...';
                        }
                    } else if (data.status === 'completed') {
                        clearInterval(statusCheckInterval);
                        conversionBar.style.width = '100%';
                        conversionPercentage.textContent = '100%';
                        console.log('转换完成，准备显示结果');
                        setTimeout(() => {
                            showConversionResult(true);
                        }, 500);
                    } else if (data.status === 'failed') {
                        clearInterval(statusCheckInterval);
                        console.log('转换失败，准备显示错误');
                        // 提供更详细的错误信息
                        let errorMessage = data.error || '转换失败';
                        if (errorMessage.includes('PDF文件没有有效页面')) {
                            errorMessage = '无法转换：PDF文件没有有效页面。请检查您的PDF文件是否损坏或为空。';
                        } else if (errorMessage.includes('division by zero')) {
                            errorMessage = '转换过程中出现计算错误。请尝试重新上传文件或联系管理员。';
                        }
                        showError(errorMessage);
                    } else if (data.status === 'uploaded') {
                        // 文件已上传但尚未开始转换
                        statusMessage.textContent = '等待转换...';
                    } else {
                        console.log('未知状态:', data.status);
                    }
                })
                .catch(error => {
                    clearInterval(statusCheckInterval);
                    showError('检查转换状态时出错: ' + error.message);
                    // 不重置UI，保持错误界面显示
                });
        }, 1000); // 每秒检查一次进度
    }

    // 显示转换结果
    function showConversionResult(success) {
        // 确保其他状态区域隐藏
        conversionStatus.classList.add('hidden');
        uploadProgress.classList.add('hidden');
        
        // 显示结果区域
        conversionResult.classList.remove('hidden');
        conversionResult.classList.add('fade-in');

        if (success) {
            successMessage.classList.remove('hidden');
            errorMessage.classList.add('hidden');
            console.log('显示成功结果');
        } else {
            successMessage.classList.add('hidden');
            errorMessage.classList.remove('hidden');
            console.log('显示失败结果');
        }
    }

    // 下载文件
    downloadBtn.addEventListener('click', function() {
        if (!taskId) return;

        window.location.href = `/download/${taskId}`;
        downloadHint.classList.remove('hidden');
        downloadBtn.disabled = true;

        // 重置UI
        setTimeout(() => {
            resetUI();
        }, 3000);
    });

    // 重试
    retryBtn.addEventListener('click', function() {
        resetUI();
    });

    // 重置UI
    function resetUI() {
        selectedFile = null;
        taskId = null;
        fileInput.value = '';
        fileInfo.classList.add('hidden');
        conversionStatus.classList.add('hidden');
        conversionResult.classList.add('hidden');
        convertBtn.classList.add('disabled');
        removeFile.classList.remove('disabled');
        uploadProgress.classList.add('hidden');
        // 确保所有状态区域都被隐藏
        errorMessage.classList.add('hidden');
        successMessage.classList.add('hidden');
        clearInterval(statusCheckInterval);
    }

    // 平滑滚动
    document.querySelectorAll('a[href^="#"]').forEach(function(anchor) {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('href');
            if (targetId === '#') return;

            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                targetElement.scrollIntoView({
                    behavior: 'smooth'
                });
            }
        });
    });
});